const axios = require("axios");
const cheerio = require("cheerio");

// 获取游侠详细游戏数据入口（游戏卡片）
async function getYouXiaDetailGame() {
  const res = await axios.get("https://0day.ali213.net/");
  return await parsePageGameCard(res.data, "https://0day.ali213.net");
}

// 获取所有游戏卡片
function parsePageGameCard(page, baseUrl) {
  return new Promise((resolve) => {
    const $ = cheerio.load(page);
    let gameCardList = [];
    $(".s2-left-list .swiper-wrapper .item-img-con a").each(async function () {
      const res = await axios.get(`${baseUrl}${$(this).attr("href")}`);
      gameCardList.push(
        handleGetDetailGameInfo(res.data, `${baseUrl}${$(this).attr("href")}`)
      );
      if (gameCardList.length >= 12) resolve(gameCardList);
    });
  });
}

// 获取单独游戏卡片详细数据
function handleGetDetailGameInfo(page, url) {
  const item = {};
  const $ = cheerio.load(page);
  item.link = url;
  item.nameC = $(".xs-c1-c .xs-c1-c-cn").text();
  item.nameE = $(".xs-c1-c .xs-c1-c-en").text();
  let index1 = 0;
  $(".xs-c1-c .xs-c1-c-time span").each(function () {
    if (index1 === 0) {
      item.time = $(this).text();
    }
    index1++;
  });
  let index2 = 0;
  $(".xs-c1-c .xs-c1-c-info .xs-c1-c-info-l").each(function () {
    if (index2 === 0) {
      item.type = $(this).text().replace("游戏类型：", "");
    }
    index2++;
  });
  let index3 = 0;
  $(".xs-c1-c .xs-c1-c-info .xs-c1-c-info-r").each(function () {
    if (index3 === 0) {
      item.create = $(this).text().replace("制作公司：", "");
    }
    index3++;
  });
  item.tag = [];
  $(".xs-c1-c .xs-c1-c-tag span").each(function () {
    item.tag.push($(this).text());
  });
  item.imgS = $(".xs-c1-l .xs-c1-l-pic-t img").attr("src");
  item.introduce = $(".xs-c1-c .xs-c1-c-tct p").text().replaceAll(" ", "");
  if ($(".xs-c1-l-pic .xs-c1-l-pic-t font").attr("onclick"))
    item.imgB = $(".xs-c1-l-pic .xs-c1-l-pic-t font")
      .attr("onclick")
      .match(/'.*?'/)[0]
      .replaceAll("'", "");
  return item;
}

module.exports = getYouXiaDetailGame;
